var express = require('express');
var multiparty = require("multiparty")
var router = express.Router();
// var { sxmenumodel } = require('../upload/model')
// var { sxmenumodel, zgh_cate_Model } = require('../upload/model')

// var { bbModel, Yrtzhifu, Yrtzhibdy, Yrttuikuan } = require('../upload/model')
var { sxmenumodel, zgh_jf_Model, zgh_cate_Model, zgh_yhj_Model, UserModel } = require('../model/model')
var { bbModel, Yrtzhifu, Yrtzhibdy, Yrttuikuan } = require('../model/model')
var { sxmenumodel, zgh_jf_Model, zgh_cate_Model, zgh_yhj_Model, UserModel } = require('../model/model')
var { sxmenumodel, fidmodel, cidmodel } = require('../model/model')

var { sxmenumodel, zgh_jf_Model, zgh_cate_Model, zgh_yhj_Model, UserModel } = require('../model/model')
var { bbModel, Yrtzhifu, Yrtzhibdy } = require('../model/model')
var { bbModel, addrModel, ayqpushModel, feedbackModel } = require('../model/model')
var multiparty = require('multiparty')

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 张天宇
router.get('/sxmenu', async (req, res) => {
  let sousuodata = req.query.datas
  var sxmenudata = await sxmenumodel.find()
  console.log(sousuodata);
  if (sousuodata == '人气') {
    var sxmenudata = await sxmenumodel.find().sort({ nums: -1 })
  } else if (sousuodata == '推荐') {
    var sxmenudata1 = []
    var indexdata = []
    sxmenudata.forEach((ele, index) => {
      var op = Math.floor(Math.random() * sxmenudata.length)
      let index1 = indexdata.findIndex((ele, index) => ele == op)
      if (index1 == -1) {

        sxmenudata1.push(sxmenudata[op])
        indexdata.push(op)

      }

    })
    sxmenudata = sxmenudata1
  }
  else if (sousuodata == '家常菜') {
    var sxmenudata = sxmenudata.filter(item => item.types === 1)
  }
  else if (sousuodata == '下饭菜') {
    var sxmenudata = sxmenudata.filter(item => item.types === 2)
  }

  res.send({
    code: 200,
    data: sxmenudata
  })
})

// 张天宇
router.post('/edittimes', async (req, res) => {
  let { id } = req.body
  const exisdata = await sxmenumodel.findById(id)
  const curums = exisdata.nums || 0

  await sxmenumodel.updateOne({ _id: id }, { nums: curums + 1 })
  res.send({
    code: 200
  })
})

// 张天宇
router.get('/foodlist', async (req, res) => {
  let _id = req.query.data


  let fooddata = await fidmodel.find({ sid: _id })

  res.send({
    code: 200,
    data: fooddata
  })
})
// 张天宇
router.get('/cidlist', async (req, res) => {
  let _id = req.query.data


  let fooddata = await cidmodel.find({ sid: _id })

  res.send({
    code: 200,
    data: fooddata
  })
})
router.get('/zhifu', async (req, res) => {
  const data = await Yrtzhifu.find()
  res.send({
    code: 200,
    msg: '数据发送成功',
    data: data
  })
})

router.get('/zhifubody', async (req, res) => {
  let tid = req.query
  const data = await Yrtzhibdy.find(tid)
  res.send({
    code: 200,
    msg: '数据外键成功',
    data: data
  })
})
router.post('/addtui', async (req, res) => {
  let body = req.body
  Yrttuikuan.create(body)
  res.send({
    code: 0,
    msg: "数据提交成功"
  })
})

router.post('/addimgyrt', async (req, res) => {
  var from = new multiparty.Form()
  from.uploadDir = 'upload'
  from.parse(req, (err, fromdata, imgdata) => {
    res.send({
      code: 200,
      msg: '上传成功',
      img: "http://localhost:3000/" + imgdata.file[0].path
      // img:'aaaaaaa'
    })
  })
})

router.get('/xiaoding/:id', async (req, res) => {
  let _id = req.params.id
  console.log(_id, "id___0000000000000000000000000000");
  await Yrtzhibdy.deleteOne({ _id })
  res.send({
    code: 200,
    msg: "删除成功",
  })
})

router.get('/yrttui', async (req, res) => {
  let data = await Yrttuikuan.find()

  res.send({
    code: 200,
    msg: "退款数据",
    data: data
  })
})

//登录接口
router.post('/login', async (req, res) => {
  let login = req.body
  let logins = await loginModel.find()
  let findLogin = logins.find(item => item.username == login.username)
  if (findLogin) {
    if (findLogin.phone == login.phone) {
      let token = "Bearer " + jwt.sign(login, 'chuan', { expiresIn: "1d" })
      await loginModel.updateOne({ username: findLogin.username }, { token: token })
      res.send({
        code: 200,
        msg: "登录成功",
        login: findLogin,
        token
      })
    } else {
      res.send({
        code: 201,
        msg: "手机号不一致"
      })
    }
  }
})
// 刘晓坷
// 发送验证码
router.get('/login', async (req, res, next) => {
  const phone = req.query.phone
  const user = await UserModel.find()
  let istrue = user.findIndex(item => {
    return item.phone == phone
  })
  console.log(phone, user, istrue);

  if (istrue == -1) {
    await UserModel.create({ phone: phone })
    // 存储验证码
    let captcha = ''
    // 存储有效时长
    // 处理验证码的逻辑函数
    function getRanderCode() {
      let code = ''
      for (let i = 0; i < 6; i++) {
        code += String(Math.ceil(Math.random() * 9))
      }
      captcha = code
      // console.log(captcha, code, 60)
      return code
    }
    getRanderCode()
    const data = await UserModel.find({ phone: phone })
    res.send({
      code: 200,
      msg: '验证码发送成功',
      captcha, data
    })
  } else {
    // 存储验证码
    let captcha = ''
    // 存储有效时长
    // 处理验证码的逻辑函数
    function getRanderCode() {
      let code = ''
      for (let i = 0; i < 6; i++) {
        code += String(Math.ceil(Math.random() * 9))
      }
      captcha = code
      return code
    }
    getRanderCode()
    const data = await UserModel.find({ phone: phone })
    res.send({
      code: 201,
      msg: '验证码发送成功',
      captcha, data
    })
  }
})



// 左盖豪分类
router.get('/zgh_cate_look', async (req, res) => {
  let data = await zgh_cate_Model.find()
  console.log(data);
  let { cate, head, title } = req.query
  if (cate != '') {
    data = data.filter(ele => ele.cate == cate)
  }
  if (head != '') {
    if (head == 1) {

      var price = 0
      data.forEach(ele => {
        price += ele.price
      })
      var avg = price / data.length
      data = data.filter(ele => ele.price <= avg)
    }
    if (head == 2) {
      data = data.sort((a, b) => b.ren - a.ren)
      console.log(data);
    }
  }
  if (title != '') {
    data = data.filter(ele => ele.title.includes(title))
  }
  res.send({ data })
})

router.post('/zgh_cate_add', async (req, res) => {
  await zgh_cate_Model.create(req.body)
  res.send('ok')
})

router.put('/zgh_cate_edit', async (req, res) => {
  await zgh_cate_Model.updateOne({ _id: req.body }, req.body)
  res.send('ok')
})

router.get('/zgh_my_look', async (req, res) => {
  let data = await zgh_cate_Model.find()
  res.send({ data })
})


// 左盖豪积分管理 zgh_jf_Model
router.get('/zgh_jf_look', async (req, res) => {
  const data = await zgh_jf_Model.find().lean()
  let cateJson = {}
  data.forEach(ele => {
    cateJson[ele._id] = ele
  })
  let catelist = []
  data.forEach(ele => {
    if (!ele.pid) {
      catelist.push(ele)
    } else {
      if (!cateJson[ele["pid"]]["children"]) {
        cateJson[ele["pid"]]["children"] = []
      }
      cateJson[ele["pid"]]["children"].push(ele)
    }
  })

  res.send({ catelist })
})

router.post('/zgh_jf_add', async (req, res) => {
  await zgh_jf_Model.create(req.body)
  res.send('ok')
})

router.put('/zgh_jf_edit', async (req, res) => {
  await zgh_jf_Model.updateOne({ _id: req.body._id }, req.body)
  res.send('ok')
})


// 左盖豪 优惠劵管理
router.get('/zgh_yhj_look', async (req, res) => {
  const data = await zgh_yhj_Model.find()
  res.send({ data })
})

router.post('/zgh_yhj_add', async (req, res) => {
  await zgh_yhj_Model.create(req.body)
  res.send('ok')
})


// ayq -- 地址获取
router.get('/address', async (req, res) => {
  const data = await addrModel.find()
  res.send({ code: 200, msg: '数据返回成功', data })
});

// ayq -- 添加地址
router.post('/adaddress', async (req, res) => {
  let obj = req.body
  obj.region = obj.region.split('/')
  if (obj.default) {
    await addrModel.updateOne({ default: true }, { default: false })
  }
  await addrModel.create(obj)
  res.send({ code: 200, msg: '数据添加成功' })
});

// ayq -- 修改地址
router.post('/edaddress', async (req, res) => {
  let obj = req.body
  obj.region = obj.region.split('/')
  if (obj.default) {
    await addrModel.updateOne({ default: true }, { default: false })
  }
  await addrModel.updateOne({ _id: obj._id }, obj)
  res.send({ code: 200, msg: '数据修改成功' })
});

// ayq -- 删除地址
router.get('/deladdress', async (req, res) => {
  let _id = req.query.id
  await addrModel.deleteOne({ _id })
  res.send({ code: 200, msg: '数据删除成功' })
});

// ayq -- 图片上传
router.post('/uploadImg', async (req, res) => {
  let form = new multiparty.Form()

  form.uploadDir = "upload"

  form.parse(req, (err, formData, imgData) => {
    res.send({ code: 200, msg: '图片上传成功', path: 'http://localhost:3000/' + imgData.file[0].path })
  })
});

// ayq -- 推送设置获取
router.get('/ayqpush', async (req, res) => {
  let data = await ayqpushModel.find()
  res.send({ code: 200, msg: '数据查询成功', data })
});

// ayq -- 推送设置修改
router.post('/ayquppush', async (req, res) => {
  let body = req.body
  await ayqpushModel.updateOne({ _id: body.id }, { push: body.checked })
  res.send({ code: 200, msg: '数据修改成功' })
});

// ayq -- 修改用户头像
router.post('/eduserimg', async (req, res) => {
  let body = req.body
  // await .updateOne({_id:body.id},{img:body.img})
  res.send({ code: 200, msg: '头像修改成功' })
});

// ayq -- 意见反馈提交
router.post('/adfeedback', async (req, res) => {
  let body = req.body
  await feedbackModel.create(body)
  res.send({ code: 200, msg: '意见提交成功' })
});
module.exports = router;
